<template>
  <div v-loading.fullscreen="loading">

    <el-row :gutter="10">
      <el-button
        type="success"
        size="large"
        @click="dialogDatas.emptyLightsOnBtnClick"
      >
        空位亮灯
      </el-button>
      <el-button
        type="info"
        size="large"
        @click="dialogDatas.emptyLightsOffBtnClick"
      >
        空位灭灯
      </el-button>
    </el-row>

    <el-row
      class="marginTop10"
      :gutter="10"
    >
      <el-col
        :span="24"
        style="text-align:left"
      >
        <el-input
          v-model="dialogDatas.filters.MATCODE"
          size="large"
          @change="getMatInfo"
          clearable
          @focus="focusFn"
          ref="matCodeInput"
        >
          <template #prepend>物料号</template>
        </el-input>

        <el-input
          v-model="dialogDatas.filters.LOCATIONID"
          size="large"
          @change="getLocationID('LOCATIONID')"
          clearable
          @focus="focusFn"
          ref="locationIdInput"
        >
          <template #prepend>库位号</template>
        </el-input>

        <el-input
          v-model="dialogDatas.filters.DATA2"
          size="large"
          @change="getLocationID('DATA2')"
          clearable
          @focus="focusFn"
          ref="bindLocationIdInput"
        >
          <template #prepend>绑定库位号</template>
        </el-input>

      </el-col>
    </el-row>

    <el-form
      :model="dialogDatas.currentData"
      class="marginTop10"
      size="large"
    >
      <el-form-item
        v-for="item in dialogDatas.formItems"
        :label="item.label"
      >
        <el-date-picker
          v-if="item.isDate"
          v-model="dialogDatas.currentData[item.value]"
          :disabled="item.disable"
          :type="item.dateOption ? item.dateOption.type : 'date'"
          :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
          :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
          :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
          :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
        />
        <el-switch
          v-else-if="item.isSwitch"
          v-model="dialogDatas.currentData[item.value]"
          :disabled="item.disable"
          inline-prompt
          active-text="启用"
          inactive-text="不启用"
          :active-value="item.trueValue"
          :inactive-value="item.falseValue"
        />
        <el-input
          v-else
          v-model="dialogDatas.currentData[item.value]"
          :disabled="item.disable"
        />
      </el-form-item>
      <div style="margin-bottom: 20px;">
        <el-button
          type="success"
          size="large"
          @click="dialogDatas.confirmBtnClick"
        >
          提交
        </el-button>
        <el-button
          type="primary"
          size="large"
          @click="dialogDatas.lightOffBtnClick"
        >
          灭灯
        </el-button>
        <el-button
          size="large"
          @click="dialogDatas.currentData = {}"
        >
          清空
        </el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import myAxios from '@/myAxios/myAxios';
import myAxiosTPX from '@/myAxios/myAxiosTPX';
import { showWarning } from '@/hooks/useMyMessageBox';
import { dayjs } from 'element-plus';
import myAxios193 from '@/myAxios/myAxios193';
import { baseUrl } from '@/myAxios/api.config';

export default {
  name: 'StockMaintainView',
  setup () {
    let loading = ref(false);
    let matCodeInput = ref(null);
    let locationIdInput = ref(null);
    let bindLocationIdInput = ref(null);

    let dialogDatas = reactive({
      filters: {
        MATCODE: '',
        LOCATIONID: '',
        DATA2: '',
        QRCODE: '',
        EMPTY_STOCKS: [],

      },
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        {
          "value": "LOCATIONID",
          "label": "库位号",
          "isDate": false,
          "disable": true,
        },
        // {
        //   "value": "HJID",
        //   "label": "货架号",
        //   "isDate": false,
        // },
        {
          "value": "MATCODE",
          "label": "物料号",
          "isDate": false,
        },
        {
          "value": "MATNAME",
          "label": "物料描述",
          "isDate": false,
        },
        {
          "value": "QTY",
          "label": "库存数量",
          "isDate": false,
        },
        // {
        //   "value": "ISLOCKED",
        //   "label": "是否锁定",
        //   "isDate": false,
        // },
        // {
        //   "value": "MATTYPE",
        //   "label": "物料类型",
        //   "isDate": false,
        // },
        // {
        //   "value": "DATA1",
        //   "label": "DATA1",
        //   "isDate": false
        // },
        // {
        //   "value": "DATA2",
        //   "label": "DATA2",
        //   "isDate": false
        // },
        {
          "value": "DATA2",
          "label": "绑定库位号",
          "isDate": false
        },
        // {
        //   "value": "DATE_TIME",
        //   "label": "精确到秒的时间(示例,可删除)",
        //   "isDate": true,
        //   "dateOption": {
        //     "type": "datetime",
        //     "format": "YYYY/MM/DD HH:mm:ss",
        //     "dateFormat": "YYYY/MM/DD",
        //     "timeFormat": "HH:mm:ss",
        //     "valueFormat": "YYYY/MM/DD HH:mm:ss"
        //   }
        // },
      ],
      confirmBtnClick: function () {
        if (!dialogDatas.currentData.LOCATIONID) {
          showWarning('库位号不能为空!');
          return;
        }
        let bxRequestName = '';
        let bxRequestParamArr = [];
        // 如果库位号是BX开头,认定为锡膏,要求填写到期日
        if (dialogDatas.currentData.LOCATIONID.startsWith('BX')) {
          if (!dialogDatas.currentData.ENDDATE) {
            showWarning('锡膏需要填写到期日!');
            return;
          }
          else {
            bxRequestName = `陈帅廷添加或修改贴片线管控信息`;
            let bxParam = `锡膏🈹锡膏🈹${dialogDatas.filters.QRCODE}🈹2🈹🈹🈹${dialogDatas.currentData.ENDDATE}🈹🈹🈹`;
            bxRequestParamArr.push(bxParam);
          }
        }
        loading.value = true;
        let now = dayjs().format('YYYY/MM/DD HH:mm:ss');
        let LocationId = dialogDatas.currentData.LOCATIONID;
        // DIP物料货架号需要手动改
        if (LocationId.includes('-')) {
          LocationId = LocationId + '-' + dialogDatas.filters.MATCODE.split('@')[2];
        }

        let params = `${LocationId}🈹${dialogDatas.currentData.HJID}` +
          `🈹${dialogDatas.currentData.MATCODE}🈹${dialogDatas.currentData.MATNAME}` +
          `🈹${dialogDatas.currentData.QTY}🈹${dialogDatas.currentData.ISLOCKED}` +
          `🈹${dialogDatas.currentData.MATTYPE}🈹${now}` +
          `🈹${dialogDatas.currentData.DATA2}🈹${dialogDatas.filters.QRCODE}🈹${1}`;

        let bdparams = `${dialogDatas.currentData.DATA2}🈹${dialogDatas.currentData.HJID}` +
          `🈹${dialogDatas.currentData.MATCODE}🈹${dialogDatas.currentData.MATNAME}` +
          `🈹${dialogDatas.currentData.QTY}🈹${dialogDatas.currentData.ISLOCKED}` +
          `🈹${dialogDatas.currentData.MATTYPE}🈹${now}` +
          `🈹${LocationId}🈹${dialogDatas.filters.QRCODE}🈹${1}`;

        let requestParamsArr = [params,];
        if (dialogDatas.currentData.DATA2) {
          if (dialogDatas.currentData.oriDATA2 != dialogDatas.currentData.DATA2) {
            let clearParams = `${dialogDatas.currentData.oriDATA2}🈹${''}` +
              `🈹${''}🈹${''}` +
              `🈹${''}🈹${''}` +
              `🈹${''}🈹${''}` +
              `🈹${''}🈹${''}` +
              `🈹${0}`;
            requestParamsArr.push(bdparams, clearParams);
          }
          else {
            requestParamsArr.push(bdparams);
          }
        }
        else {

        }

        let dipParams = `${LocationId}🈹${dialogDatas.currentData.LOCATIONID}`;
        let dipParamsArr = LocationId == dialogDatas.currentData.LOCATIONID ? [] : [dipParams];
        let matcodeParams = `${dialogDatas.currentData.MATCODE}🈹${dialogDatas.filters.QRCODE}🈹${now}`;
        let matcodeRecordParams = `${dialogDatas.currentData.MATCODE}🈹${dialogDatas.filters.QRCODE}🈹${now}`
          + `🈹${now}🈹${'入库'}🈹${dialogDatas.currentData.QTY}🈹🈹🈹🈹${LocationId}`;

        let dataContent = {
          requestNames: ['陈帅廷添加或修改贴片线库位信息', '陈帅廷修改贴片线库位DIP状态', '陈帅廷添加或修改贴片线物料信息', '陈帅廷添加或修改贴片线出入库记录'],
          requestParamsArrs: [requestParamsArr, dipParamsArr, [matcodeParams], [matcodeRecordParams]],
          requestFactorys: ["Q902", "Q902", "Q902", "Q902"],
        };
        if (bxRequestName) {
          dataContent.requestNames.push(bxRequestName);
          dataContent.requestParamsArrs.push(bxRequestParamArr);
          dataContent.requestFactorys.push('9900');
        }
        myAxios193.post('users/postDiffMutipleRequests', JSON.stringify(dataContent)).then(async res => {
          if (res.returnData.message.includes('全部成功')) {
            loading.value = false;

            //成功后灭灯
            sendLightSigns([
              { LOCATIONID: dialogDatas.currentData.LOCATIONID },
              { LOCATIONID: dialogDatas.currentData.DATA2 },
            ]);
            dialogDatas.currentData.oriDATA2 = dialogDatas.currentData.DATA2;
            // dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!',
            });

            let LOCATIONID = dialogDatas.currentData.LOCATIONID;
            let ENDDATE = dialogDatas.currentData.ENDDATE;
            dialogDatas.currentData = {};
            dialogDatas.filters.MATCODE = '';
            dialogDatas.filters.LOCATIONID = '';
            dialogDatas.filters.DATA2 = '';
            dialogDatas.filters.QRCODE = '';
            // 锡膏
            if (LOCATIONID.startsWith('BX')) {
              dialogDatas.currentData.LOCATIONID = LOCATIONID;
              dialogDatas.filters.LOCATIONID = LOCATIONID;
              dialogDatas.currentData.ENDDATE = ENDDATE;
            }
            // getTableDatas();
            matCodeInput.value.focus();

          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      lightOffBtnClick: function () {
        sendLightSigns([
          { LOCATIONID: dialogDatas.filters.LOCATIONID },
          { LOCATIONID: dialogDatas.filters.DATA2 },
        ]);
      },
      cancelBtnClick: function () {

      },

      emptyLightsOnBtnClick: function () {
        loading.value = true;
        // 空盘亮红灯
        myAxios.get('陈帅廷获取贴片线空盘库位', '').then(res => {
          console.log('res :>> ', res);
          dialogDatas.filters.EMPTY_STOCKS = res;

          sendLightSigns(res, 32);
          loading.value = false;
        });
      },
      emptyLightsOffBtnClick: function () {
        loading.value = true;
        // 空盘灭灯
        if (dialogDatas.filters.EMPTY_STOCKS.length) {
          sendLightSigns(dialogDatas.filters.EMPTY_STOCKS,);
          loading.value = false;
        }
        else {
          myAxios.get('陈帅廷获取贴片线空盘库位', '').then(res => {
            console.log('res :>> ', res);
            dialogDatas.filters.EMPTY_STOCKS = res;

            sendLightSigns(res, 0);
            loading.value = false;
          });

        }
      },
    });

    let sendLightSigns = async function (datas, colorNum = 0) {
      // loading.value = true;

      let dataContent = {
        "Details": [
        ]
      };
      let demo = {
        "LocationId": "L8354A2055",
        "LightColor": 0,
        "Twinkle": 0,
        "IsLocked": 0,
        "IsMustCollect": 0,
        "Quantity": 5,
        "SubText": "11",
        "BatchCode": "BatchCode",
        "Name": "Name",
        "R1": "第一行",
        "R2": "第二行",
        "R3": "第三行",
        "SubTitle": "副标题",
        "Title": "主标题",
        "Unit": "单位",
        "RelateToTower": true
      };
      for (let i = 0; i < datas.length; i++) {
        let el = datas[i];
        let detail = { ...demo, LocationId: el.LOCATIONID, LightColor: colorNum };
        dataContent.Details.push(detail);
      }
      if (dataContent.Details.length) {
        if (baseUrl == 'cstApi/') {
          console.log('result :>> ', dataContent.Details, '测试默认亮灭灯成功');
        }
        else {
          let result = await myAxiosTPX.post('api/Light/PostInfo/', JSON.stringify(dataContent));
          console.log('result :>> ', result);
        }
      }
      loading.value = false;
    };

    let getTableDatas = async function () {
      if (!dialogDatas.filters.LOCATIONID) {
        showWarning('领料单不能为空');
      }
      else {
        loading.value = true;

        let stockParams = `${dialogDatas.filters.LOCATIONID}`;
        let stockTable = await myAxios.get('陈帅廷获取贴片线库位信息', stockParams);

        let length = stockTable.length;
        if (length == 0) {
          showWarning('未查询到库位信息');
          loading.value = false;
        }
        else {
          dialogDatas.currentData = { ...stockTable[0] };
          loading.value = false;
        }
      }

    };

    let getMatInfo = async function () {
      if (!dialogDatas.filters.MATCODE) {
        showWarning('物料号不能为空');
      }
      else {
        loading.value = true;

        let matcode = dialogDatas.filters.MATCODE.split('@')[0];
        let number = dialogDatas.filters.MATCODE.split('@')[1];
        dialogDatas.filters.QRCODE = matcode + '@' + dialogDatas.filters.MATCODE.split('@')[2];
        console.log('dialogDatas.filters.MATCODE :>> ', dialogDatas.filters.MATCODE);
        console.log('number :>> ', number);
        console.log('dialogDatas.filters.QRCODE :>> ', dialogDatas.filters.QRCODE);

        let stockParams = `${matcode}`;
        let stockTable = (await myAxios.getSap('SAP根据物料号查询物料描述2', stockParams, '9911')).TableSet.ZB_DESCRIPTION;
        console.log('stockTable :>> ', stockTable);

        let length = stockTable.length;
        if (length == 0) {
          showWarning('未查询到物料信息');
          loading.value = false;
        }
        else {
          dialogDatas.currentData.MATCODE = matcode;
          dialogDatas.currentData.MATNAME = stockTable[0].DATA1;
          dialogDatas.currentData.QTY = number;
          loading.value = false;
          // 锡膏
          if (!dialogDatas.filters.LOCATIONID.startsWith('BX')) {
            locationIdInput.value.focus();
          }
        }
      }

    };

    let focusFn = function (event) {
      event.srcElement.setAttribute('readonly', 'readonly');
      setTimeout(() => {
        event.srcElement.removeAttribute('readonly');
      }, 200);

      // console.log('event :>> ', event);
    };

    let getLocationID = async function (key) {
      if (!dialogDatas.filters[key]) {
        showWarning('库位号不能为空');
      }
      else {
        if (key == 'LOCATIONID') {
          let stockParams = `${dialogDatas.filters.LOCATIONID}`;
          let stockTable = await myAxios.get('陈帅廷获取贴片线库位信息', stockParams);

          let length = stockTable.length;
          if (length == 0) {
            // DIP物料不需要库位信息
            if (dialogDatas.filters.LOCATIONID.indexOf('-') != -1) {
              loading.value = false;
              dialogDatas.currentData.LOCATIONID = dialogDatas.filters.LOCATIONID;
              dialogDatas.currentData.DATA2 = '';
              dialogDatas.currentData.oriDATA2 = '';
              // 如果库位号是BX开头,认定为锡膏,要求填写到期日
              if (dialogDatas.filters.LOCATIONID.startsWith('BX')) {
                dialogDatas.currentData.LOCATIONID = dialogDatas.filters.LOCATIONID;
                dialogDatas.currentData.DATA2 = '';
                dialogDatas.currentData.oriDATA2 = '';
                let newFormItem = {
                  "value": "ENDDATE",
                  "label": "到期日",
                  "isDate": true,
                };
                //  如果已经有ENDDATE,则不添加
                if (dialogDatas.formItems.filter(item => item.value == 'ENDDATE').length == 0) {
                  dialogDatas.formItems.splice(1, 0, newFormItem);
                }
                // dialogDatas.currentData.DATA2 = dialogDatas.currentData.DATA2;
              }
              else {
                // 如果不是BX开头,则不添加到期日,如果已经有到期日,则移除
                let newFormItem = dialogDatas.formItems.filter(item => item.value == 'ENDDATE');
                if (newFormItem.length > 0) {
                  dialogDatas.formItems.splice(dialogDatas.formItems.indexOf(newFormItem[0]), 1);
                }
              }
              // 点亮新的灯
            }
            else {
              loading.value = false;
              showWarning('未查询到库位信息');
            }
            return;
          }
          else {
            // 判断库位状态
            if (stockTable[0]['STATE'] != 0) {
              loading.value = false;
              showWarning('该库位为非空盘库位，不能绑定！');
              return;
            }

            // 原来的灯先变回红色
            sendLightSigns([
              { LOCATIONID: dialogDatas.currentData.LOCATIONID },
              { LOCATIONID: dialogDatas.currentData.oriDATA2 },
            ], 32);

            dialogDatas.currentData.LOCATIONID = stockTable[0].LOCATIONID;
            dialogDatas.currentData.DATA2 = stockTable[0].DATA2;
            dialogDatas.currentData.oriDATA2 = stockTable[0].DATA2;
            // 点亮新的灯
            sendLightSigns([
              { LOCATIONID: dialogDatas.currentData.LOCATIONID },
              { LOCATIONID: dialogDatas.currentData.DATA2 },
            ], 64);

            loading.value = false;
          }
        }
        else if (key == 'DATA2') {
          // 判断库位状态

          let stockParams = `${dialogDatas.filters.DATA2}`;
          let stockTable = await myAxios.get('陈帅廷获取贴片线库位信息', stockParams);

          let length = stockTable.length;
          if (length == 0) {
            loading.value = false;
            showWarning('未查询到库位信息');
            return;
          }
          else {
            // 判断库位状态
            if (stockTable[0]['STATE'] != 0) {
              loading.value = false;
              showWarning('该库位为非空盘库位，不能绑定！');
              return;
            }

            if (dialogDatas.filters.DATA2 != dialogDatas.currentData.DATA2) {
              ElMessageBox.confirm(
                '确认要修改绑定货架号?',
                '二次确认',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
              ).then(() => {
                //之前扫的货架号(不一定是数据库绑定的,有可能扫错了)变回红色
                sendLightSigns([
                  { LOCATIONID: dialogDatas.currentData.DATA2 },
                ], 32);
                dialogDatas.currentData.DATA2 = dialogDatas.filters.DATA2;

                //点亮新货架号,原来的变回红色
                sendLightSigns([
                  { LOCATIONID: dialogDatas.currentData.DATA2 },
                ], 64);
                sendLightSigns([
                  { LOCATIONID: dialogDatas.currentData.oriDATA2 },
                ], 32);
              }).catch(() => {
                ElMessage({
                  type: 'info',
                  message: '已取消',
                });
              });
            }
          }

        }
      }
    };

    onMounted(() => {
      // getTableDatas();
    });

    return {
      matCodeInput,
      locationIdInput,
      focusFn,

      getTableDatas,
      getMatInfo,
      getLocationID,
      loading,
      dialogDatas,
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

